#!/bin/sh
# Copyright (c) 2011, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.
# created on 2011-02-05

# Digs into your browser cache and gathers
# HTML pages to a temporary location for you to view.

main(){
 local WEBBROWSER="google-chrome"
 local CACHE="$HOME/.cache/google-chrome/Cache"
 local OUT=out
 local IDX=index.html #implicit $OUT/
 cd $CACHE || exit 1
 if [ ! -d $OUT ] ; then
    mkdir -p $OUT || exit 1
    extract_htmls $OUT
 fi
 cd $OUT || exit 1
 if [ ! -f $IDX ] ;then
    make_index $IDX
 fi
 $WEBBROWSER file://$CACHE/$OUT/$IDX
}

extract_htmls(){
    local OUT="$1"
    printf "extracting pages: " >&2
    file * |
    grep -vE 'PNG|JPEG|GIF|PC bitmap|: *data$' |
    while read a ;do
     local FILE=`echo "$a" | get_file_name`
     printf " $FILE" >&2
     local TYPE=`echo "$a" | get_file_type`
     local OUTFILE="$OUT/$FILE.html"
     if
      echo "$TYPE" |
      grep -q "gzip"
     then
      if
       zcat "$FILE" |
       file - |
       grep -qv ": *data$"
      then
       zcat "$FILE" > "$OUTFILE" || exit 1
      fi
     else
      ln -sf "../$FILE" "$OUTFILE" || exit 1
     fi
    done
    echo >&2
}

get_file_name(){
    sed "s/^\([^:]*\): .*$/\1/" "$@"
}

get_file_type(){
    sed "s/^[^:]*: *\([^ ].*\)$/\1/" "$@"
}

make_index(){
    local IDX="$1"
    echo "creating index $IDX" >&2
     cat > $IDX << EOF
<html><head>
<title>index of your browser cache created by $0</title>
</head>
<body>
<ul>
EOF
     file -Li * |
     while read a ;do
      local FILE=`echo "$a" | get_file_name`
      local TYPE=`echo "$a" | get_file_type`
      printf " $FILE" >&2
      if
       echo "$TYPE" |
       grep -q "^text/html\>"
      then
       local DESC=`
        grep '<title>.*</title>' "$FILE" |
        LC_ALL=c sed 's~^.*<title>\(.*\)</title>.*$~\1~' |
        html_escape `
      else
       local DESC=`
         echo "$TYPE" | html_escape
         echo " ... "
         file -L "$FILE" |
         get_file_type |
         html_escape `
      fi
      echo "<li><a href=\"${FILE}\">${FILE} - $DESC</a></li>" >> $IDX
     done
     cat >> $IDX << EOF
</ul>
</body></html>
EOF
    echo >&2
}

html_escape(){
    sed '
        s/&/\&amp;/g
        s/</\&lt;/g
        s/>/\&gt;/g
         ' "$@"
}

main "$@"
